import permision from "@/js_sdk/wa-permission/permission.js"

// 查询权限
export function getSetting(scope, text, block, errBlock = () => {}) {
	// #ifdef APP-PLUS
	if (uni.getSystemInfoSync().platform === "ios") {
		var result = permision.judgeIosPermission(scope)
		if (result) { // 由于 iOS 无法判断是第一次安装未授权过，还是拒绝了。所以先不用getSetting检查，直接调相册、通讯录等功能，等报错了再调getSetting
			block()
		} else {
			uni.showModal({
				content: text,
				confirmText: '去设置',
				cancelText: '取消',
				showCancel: true,
				success: (res) => {
					if (res.confirm) {
						permision.gotoAppPermissionSetting()
					} else {
						errBlock(res)
					}
				},
			})
		}
	} else {
		permision.requestAndroidPermission(scope).then(result => {
			console.log("result", result)
			// result == 1  "已获得授权"
			//  result == 0 "未获得授权"
			if (result == 1) {
				block()
			} else if (result == 0) {
				errBlock(result)
			} else {
				uni.showModal({
					content: text,
					confirmText: '去设置',
					cancelText: '取消',
					showCancel: true,
					success: (res) => {
						if (res.confirm) {
							permision.gotoAppPermissionSetting()
						} else {
							errBlock(res)
						}
					},
				})
			}
		}).catch((e) => {
			console.log("requestAndroidPermission:error", e)
		})

	}

	// #endif
	// #ifdef MP
	uni.authorize({
		scope: scope,
		success: () => {
			console.log('已授权')
			block()
		},
		fail: () => {
			console.log('未授权')
			// 打开授权提示弹框
			uni.showModal({
				content: text,
				confirmText: '确认',
				cancelText: '取消',
				showCancel: true,
				success: (res) => {
					if (res.confirm) {
						uni.openSetting({
							success: (data) => {
								if (data.authSetting[scope]) {
									block()
								} else {
									errBlock(data)
								}
							},
							fail(err) {
								errBlock(err)
							},
						})
					} else {
						errBlock(res)
					}
				},
			})
		},
	})
	// #endif
}



export function downloadImageFromURL(url = "") {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url,
			fail: function(res) {
				uni.showModal({
					title: '提示',
					content: '保存失败',
				})
				reject(res)
			},
			success: function(res) {
				resolve(res)
			},
		})

	})
}